import { CHANGED_SELECTION, EDITED_MESSAGE, SEND_MESSAGE } from "./action";
import { Action, State } from "./interface";

export const initialState: State = {
  selectedId: 0,
  messages: {
    0: "Hello, Taylor",
    1: "Hello, Alice",
    2: "Hello, Bob"
  }
};

export function messengerReducer(draft: State, action: Action) {
  switch (action.type) {
    case CHANGED_SELECTION: {
      draft.selectedId = action.payload?.contactId ?? draft.selectedId;
      break;
    }
    case EDITED_MESSAGE: {
      draft.messages[draft.selectedId] = action.payload?.message ?? draft.messages[draft.selectedId];
      break;
    }
    case SEND_MESSAGE: {
      draft.messages[draft.selectedId] = "";
      break;
    }
    default: {
      throw Error("未知 action：" + action.type);
    }
  }
}
